package com.cool.modules.base.controller.admin.sys;

import cn.hutool.json.JSONObject;
import com.cool.core.annotation.CoolRestController;
import com.cool.core.base.BaseController;
import com.cool.core.request.R;
import com.cool.core.util.CoolSecurityUtil;
import com.cool.core.util.TenantUtil;
import com.cool.modules.base.entity.sys.BaseSysTenantManagerUserEntity;
import com.cool.modules.base.service.BaseSysTenantManagerUserService;
import com.mybatisflex.core.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * 租户管理员关系
 */
@Tag(name = "租户管理员关系", description = "租户管理员关系")
@CoolRestController(api = {"add", "delete", "update", "page", "list", "info"})
public class AdminBaseSysTenantManagerUserController extends BaseController<BaseSysTenantManagerUserService, BaseSysTenantManagerUserEntity> {
    @Override
    protected void init(HttpServletRequest request, JSONObject requestParams) {

    }

    @Operation(summary = "获取用户可管理的租户列表")
    @PostMapping("/getManagerList")
    public R getManagerList(@RequestAttribute JSONObject requestParams){
        return R.ok(this.service.getTenantManagerUsersByUserId(CoolSecurityUtil.getCurrentUserId()));
    }

    @Operation(summary = "获取租户列表")
    @PostMapping("/getTenantList")
    public R getTenantList(@RequestAttribute JSONObject requestParams){
        if(CoolSecurityUtil.getAdminUsername().equals("admin")){
            return R.ok(this.service.list());
        }
        Long[] tenantIds = TenantUtil.getTenantIds();
        if (tenantIds == null || tenantIds.length == 0) {
            return R.ok(List.of());
        }
        List<BaseSysTenantManagerUserEntity> tenantList =
                this.service.list(QueryWrapper.create().in(BaseSysTenantManagerUserEntity::getManagerTenantId, tenantIds));
        return R.ok(tenantList);
    }

    @Operation(summary = "获取详情")
    @GetMapping("/getInfo")
    public R getInfo(@RequestParam() Long id){
        return R.ok(this.service.info(id));
    }
}